<template>
  <BasicModal title="付款打印" @register="registerModal" @cancel="afterClose"
              :showCancelBtn="false" :showOkBtn="false" :canFullscreen="false" :centered="true"
              :width="'90%'"
              :bodyStyle="{height:'calc(100vh - 120px)', overflowY:'hidden'}"
  >
    <div class="jeecg-basic-table jeecg-basic-table-form-container" style="margin-top: -14px">
      <a-form @keyup.enter.native="searchQuery">
        <a-row :gutter="8" type="flex">
          <a-col flex="180px">
            <a-form-item label="日期" :label-col="{ style: { width: '50px' } }" >
              <a-date-picker
                v-model:value="queryParam.beginDate"
                valueFormat="YYYY-MM-DD"
                placeholder=""
                style="width: 120px"
              />
            </a-form-item>
          </a-col>

          <a-col flex="140px">
            <a-form-item label="支付方式" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ span: 17 }">
              <JDictSelectTag
                placeholder="全部"
                v-model:value="queryParam.sffs"
                dictCode="sffsType"
                :dropdownMatchSelectWidth="false"
                :showArrow="false"
                :allowClear="true"
              />
            </a-form-item>
          </a-col>

          <a-col flex="195px">
            <a-form-item label="订单编号" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ span: 17 }">
              <a-input placeholder="" v-model:value.trim="queryParam.orderId"></a-input>
            </a-form-item>
          </a-col>

          <a-col flex="200px">
            <a-form-item label="操作人" :label-col="{ style: { width: '55px' } }">
              <JDictSelectTag v-model:value="queryParam.createBy" dictCode="sys_user,realname,id" authFilter="authUser" :allowClear="false"/>
            </a-form-item>
          </a-col>

          <a-col flex="300px">
            <a-form-item label="报销项目" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ span: 17 }">
              <a-input placeholder="" v-model:value.trim="queryParam.dwmc"></a-input>
            </a-form-item>
          </a-col>

          <a-col flex="auto" style="float:right; width:100px;">
            <span style="float:right;overflow:hidden;" class="table-page-search-submitButtons">
              <a-button color="success" @click="searchQuery" preIcon="ant-design:search" class="mr-5px">查询</a-button>
              <a-button color="warning" @click="jsonPrint" preIcon="ant-design:plus-outlined">打印</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <AccountPrintModal @register="registerAccountPrintModal" @success="handleSuccess"></AccountPrintModal>
    <AccountPrintView @register="registerAccountPrintView" @success="handleSuccess"></AccountPrintView>
  </BasicModal>
</template>

<script lang="ts" name="full-accountPrint" setup>
import { reactive, ref, toRaw, unref } from "vue";
import { BasicTable } from "/@/components/Table";
import { TableAction } from "/@/components/Table";
import { BasicModal, useModal, useModalInner } from "/@/components/Modal";
import { useListPage } from "/@/hooks/system/useListPage";
import { columns } from "../types/AccountPrint.data";
import { batchDelete, deleteOne, list, view } from "../types/AccountPrint.api";
import { useUserStore } from "/@/store/modules/user";
import { useMessage } from "/@/hooks/web/useMessage";
import { printJS } from "/@/hooks/web/usePrintJS";
import JDictSelectTag from "/@/components/Form/src/jeecg/components/JDictSelectTag.vue";
import AccountPrintModal from "./AccountPrintModal.vue";
import AccountPrintView from "./AccountPrintView.vue";
import dayjs from "dayjs";

const { createMessage: $message } = useMessage();
// Emits声明
const emit = defineEmits(['register','success']);
//初始化 -------------------------------------------------------------
//定义查询表单，查询条件
const date = new Date()
let isReload = ref(false); //是否有数据操作
const queryParam = reactive({
  createBy: useUserStore().getUserInfo?.id,
  beginDate: dayjs(date).format("YYYY-MM-DD"),
  sffs: "",
  orderId: "",
  dfhm: ""
})

//表单赋值
const [registerModal, { closeModal }] = useModalInner(async (data) => {
  searchQuery();
});

//注册model
const [registerAccountPrintModal, { openModal }] = useModal();
//注册table数据
const { prefixCls, tableContext } = useListPage({
  tableProps: {
    api: list,
    columns: columns,
    size: 'small',
    canResize: true,
    showTableSetting: false,
    showIndexColumn: false,    //行号
    showActionColumn: true,
    useSearchForm: false,
    resizeHeightOffset: 16,
    beforeFetch: (params) => Object.assign(params, unref(queryParam)),
    actionColumn: {
      width: 70
    }
  },
});

//注册table数据 rowSelection, selectedRowKeys, selectedRows
const [registerTable, {reload, setProps, getRawDataSource, setSelectedRowKeys, redoHeight}, { rowSelection, selectedRowKeys, selectedRows }] = tableContext

function searchQuery() {
  setSelectedRowKeys([]);
  setProps({searchInfo:toRaw(queryParam)});
  reload()
}

/**
 * 新增事件
 */
function handleAdd() {
  openModal(true, {
    isUpdate: false,
    showFooter: true
  });
}

/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true
  });
}

/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, reload).then(() => {
    isReload.value = true
  });
}

/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  await batchDelete({ ids: selectedRowKeys.value }, reload);
}

/**
 * 删除与编辑成功回调
 */
// Cancel event | Modal 完全关闭后的回调
function afterClose() {
  //console.info("isReload.value@@@@@@@@", isReload.value)
  if (isReload.value) {
    emit('success');
  }
}

/**
 * 关闭窗口后回调函数
 */
function handleCancel() {
  emit('success');
}

/**
 * 操作栏
 */
function getTableAction(record) {
  return [
    {
      label: '编辑',
      icon: "ant-design:form-outlined",
      onClick: handleEdit.bind(null, record),
    },
    {
      label: '删除',
      color: 'error',
      icon: 'ant-design:rest-twotone',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record),
      },
    },
  ];
}

function handleSuccess() {

}

const [registerAccountPrintView, { openModal: openAccountPrintView }] = useModal();
/**
 * 打印事件
 */
function handleAccountPrintView() {
  //1、获取被选中的行信息
  let rows = unref(selectedRows)
  if (rows.length <= 0) {
    $message.warning("请选择") //请勾选不能为空！
    return false
  }

  //2、判断选中的单位是否是同一家
  var pId = [], ids = ''
  for (var i = 0; i < rows.length; i++) {
    if (i == 0) {
      ids = rows[i].id;
    } else {
      ids = ids + "," + rows[i].id;
    }
  }
  openAccountPrintView(true,{ids})
}

//************打印*******************************************
let year  = dayjs(date).format('YYYY')
let month = dayjs(date).format('MM')
let day   = dayjs(date).format('DD')

let printList = reactive<any>({});  //业务收支明细

//点击执行
function jsonPrint() {
  getPrintDate()
}

//获取数据 , 1625729754499584002, 1625729754524749825, 1625664690119708676, 1625664690119708677, 1625729754524749826, 1625729754524749827
async function getPrintDate() {
  //1、获取被选中的行信息
  let rows = unref(selectedRows)
  if (rows.length <= 0) {
    $message.warning("请选择") //请勾选不能为空！
    return false
  }

  let ids = ''
  for (var i = 0; i < rows.length; i++) {
    if (i == 0) {
      ids = rows[i].id;
    } else {
      ids = ids + "," + rows[i].id;
    }
  }
  //let record = {ids: '1625729754499584002,1625664690119708674,1625729754524749825,1625664690119708677'}

  let params = {
    ids: ids,
    createBy: queryParam.createBy,
    beginDate: queryParam.beginDate,
  }

  view(params).then((res) => {
    try {
      if (res.success != true) {
        $message.warning(res.message)
        return false;
      }
      let result = res.result;
      //1、业务数据 - 初始化
      Object.assign(printList, result);
      jobPrintDate(result)
    } catch (e) {
      alert("initData : " + e);
      return false;
    }
  }).finally(() => {
    //data.loading = false
  });
}

//加工数据
async function jobPrintDate(data) {
  printList =  data
  if (!printList) {
    return false
  }
  var datahtml = '';
  //datahtml += '<view style="height: auto; display: block; ">';
  for(let k in printList) {
    datahtml += datahtml == '' ? '' : pageBreakAfter(printList[k].sffs);
    datahtml += '<h1 class="h1-page">费用报销单</h1>';
    datahtml += '<div class="header">';
    datahtml += '<div class="span-page left">';
    datahtml += '  <span>' + printList[k].sffsZW + '</span>';
    datahtml += '  <span>' + pageHeaderOrderId(printList[k]) + '</span>';
    datahtml += '</div>';
    datahtml += '<div class="span-page right"><span style="width: 30mm">填表日期：</span>';
    datahtml += '<span style="width: 15mm"><label>' + year + '</label>年</span>';
    datahtml += '<span style="width: 10mm"><label>' + month + '</label>月</span>';
    datahtml += '<span style="width: 10mm"><label>' + day + '</label>日</span></div>';
    datahtml += '<div></div></div>';
    datahtml += '<table border="1" cellspacing="0" class="table-page">';
    datahtml += '<tr>';
    datahtml += '  <td class="td-left">采购单位</td>';
    datahtml += '  <td class="text-left" style="width: 110mm; height: 4mm; padding: 0 5px; line-height: 105%;">' + printList[k].dwmc + '</td>';
    datahtml += '  <td class="td-left">报销人</td>';
    datahtml += '  <td class="text-left"></td>';
    datahtml += '</tr>';
    datahtml += '<tr>';
    datahtml += '  <td class="td-left">报销事由</td>';
    datahtml += '  <td class="text-left" colspan="3" style="height: 46.5mm; padding: 2px 5px;">'
    datahtml += '   <div style="height: 46.5mm; vertical-align:top; line-height: 110%; overflow:hidden;display:-webkit-box;text-overflow:ellipsis;-webkit-box-orient:vertical;-webkit-line-clamp:13;">';
    datahtml += printList[k].bz.replace(/\n/g,'<br/>') ;
    datahtml += '   </div>';
    datahtml += '   </td>';
    datahtml += '</tr>';
    datahtml += '<tr>';
    datahtml += '  <td colspan="4" class="text-left">';
    datahtml += '  <div class="left">';
    datahtml += '    <label>报销单据</label>';
    datahtml += '    <span style="padding: 5px 20px 0px 15px;"></span>';
    datahtml += '    <label style="margin-right: 8px">张</label>';
    datahtml += '    <label>合计金额（大写）</label>';
    datahtml += '    <span class="zhlangje">' +printList[k].B0 + '</span>';
    datahtml += '    <label class="font-bold">拾</label>';
    datahtml += '    <span class="zhlangje">' +printList[k].B1 + '</span>';
    datahtml += '    <label class="font-bold">万</label>';
    datahtml += '    <span class="zhlangje">' +printList[k].B2 + '</span>';
    datahtml += '    <label class="font-bold">仟</label>';
    datahtml += '    <span class="zhlangje">' +printList[k].B3 + '</span>';
    datahtml += '    <label class="font-bold">佰</label>';
    datahtml += '    <span class="zhlangje">' +printList[k].B4 + '</span>';
    datahtml += '    <label class="font-bold">拾</label>';
    datahtml += '    <span class="zhlangje">' +printList[k].B5 + '</span>';
    datahtml += '    <label class="font-bold">元</label>';
    datahtml += '    <span class="zhlangje">' +printList[k].B6 + '</span>';
    datahtml += '    <label class="font-bold">角</label>';
    datahtml += '    <span class="zhlangje">' +printList[k].B7 + '</span>';
    datahtml += '    <label class="font-bold">分</label>';
    datahtml += '  </div>';
    datahtml += '  <div class="right">';
    datahtml += '    <label>￥</label>';
    datahtml += '    <span class="zhlangje" style="font-size: 16px margin-left: -5px">' +printList[k].je + '</span>';
    datahtml += '  </span>';
    datahtml += '  </td>';
    datahtml += '</tr>';
    datahtml += '</table>';
    datahtml += '<div class="footer" style="font-size: 12px; padding: 5px 8px">';
    datahtml += '<div style="width: 50mm">会计主管</div>';
    datahtml += '  <div style="width: 44mm">审核</div>';
    datahtml += '  <div style="width: 44mm">出纳</div>';
    datahtml += '  <div style="width: 25mm">填报人</div>';
    datahtml += '</div>';

    let list = printList[k].accounts || ''
    let accounts = list.optionList
    if (printList[k].sffs == '3' && list && accounts) {
      datahtml += '<h4 class="h4-page">支出明细</h4>';
      datahtml += '<table border="1" cellspacing="0" class="table-account">';
      datahtml += '<tr>';
      datahtml += '  <th style="width: 3mm;"></th>';
      datahtml += '  <th style="width: 22mm;">订单号</th>';
      datahtml += '  <th style="width: 50mm;">订单名称</th>';
      datahtml += '  <th style="width: 15mm; text-align:right">支出</th>';
      datahtml += '  <th style="width: 10mm;">操作人</th>';
      datahtml += '  <th style="width: 18mm;">操作时间</th>';
      datahtml += '  <th style="">备注</th>';
      datahtml += '</tr>';
      let k = 1;
      for(let o in accounts) {
        datahtml += '<tr>';
        datahtml += '  <td>'+ (k++) +'</td>';
        datahtml += '  <td>'+ accounts[o].orderId +'</td>';
        datahtml += '  <td class="text-left">'+ accounts[o].travelLine +'</td>';
        datahtml += '  <td class="text-right">'+ Math.round(accounts[o].fkje).toFixed(2) +'</td>';
        datahtml += '  <td>'+ accounts[o].lrr +'</td>';
        datahtml += '  <td>'+ accounts[o].lrsj +'</td>';
        datahtml += '  <td class="text-left">'+ accounts[o].bz +'</td>';
        datahtml += '</tr>';
      }
      datahtml += '<tr>';
      datahtml += '  <td></td>';
      datahtml += '  <td>合计</td>';
      datahtml += '  <td></td>';
      datahtml += '  <td class="text-right">'+ list.sumfkje +'</td>';
      datahtml += '  <td></td>';
      datahtml += '  <td></td>';
      datahtml += '  <td></td>';
      datahtml += '</tr>';
      datahtml += '</table>';
    }
  }
  //datahtml += '</view>';

  calPrintDate(datahtml)
}

//打印数据
async function calPrintDate(datahtml) {
  printJS({
    printable: [], //表格的数据
    properties: [],
    type: "json",
    header: datahtml,
    targetStyles: ['*'],
    style: printPageStyle(),
    scanStyles: false
  });
}

function printPageStyle() {
  let style =`
    @page{ size: auto A4 landscape; margin: 8mm; }
    .h1-page{
      position: relative;
      font-weight: 600;
      margin: 0 auto;
      text-align: center;
      top: 10mm;
      font-size: 22px;
      letter-spacing: 15px;
    }
    .header {
      width: 190mm;
      margin: 0 auto;
      margin-top: 12mm;
      margin-bottom: 1mm;
    }
    .header .span-page{
      width:80mm;
      font-size: 12px;
    }
    .header .span-page span{
      display: inline-block;
      height: 18px;
      line-height: 18px;
    }
    .header .span-page span label{
      font-size: 16px;
      font-weight: 500;
      padding: 0 2px;
      height: 14px;
      line-height: 16px;
    }
    .left {
      text-align:left;
      float:left;
    }
    .right {
      text-align:right;
      float:right;
    }
    table, table tr th, table tr td { border: 1px solid #808080; }
    table { border-collapse: collapse; font-size: 12px; width: 190mm; margin: 0 auto; text-align:center; }
    .table-page .text-left, .table-account .text-left { text-align:left; }
    .table-page .text-right, .table-account .text-right { text-align:right; }
    .table-page td { padding: 5px 12px; }
    .table-page td span{
      padding: 5px 1px 0px 3px;
      font-size: 14px;
      border-bottom: 1px solid #808080;
    }
    .table-page td label{
      padding: 5px 0px 1px 0px;
      font-size: 12px;
    }
    .table-page td .fr { float: right }
    .td-left {
      width: 13mm;
      text-align-last: justify;
    }
    .font-bold {
      font-weight: bold
    }
    .h4-page{ width: 190mm; margin: 0 auto; margin-bottom: 3px; margin-top: 20px; }
    .table-account th, .table-account td { padding: 2px 5px; }
    .footer{
      width: 190mm;
      height: 25px;
      margin: 0 auto;
    }
    .footer div{
      display: inline-block;
      float: left;
    }
  `
  return style
}

function pageBreakAfter(sffs) {
  if (sffs == '3') {
    return '<div style="page-break-after: always;"></div>'
  } else {
    return ''
  }
}

function pageHeaderOrderId(p){
  let sffs = p.sffs
  let list = p.accounts || ''
  let accounts = list.optionList || []
  let l = accounts.length
  let orderId = p.orderId;
  //console.info("p.orderId2", (l - 1) , p.orderId, list)
  if (sffs == '3' && list && accounts && l > 1) {
    let o1 = accounts[0].orderId
    let o2 = accounts[l - 1].orderId
    if (o1 != o2) {
      orderId =  o1 + " ~ " + o2;
    }
  }
  return orderId
}

</script>
<style scoped>
:deep .jeecg-modal-content > .scroll-container {
  padding: 0!important;
  border: 1px red solid;
  border-radius: 45%;
}
</style>
